import React from "react";
import {Avatar, Form, Spin} from 'antd';

import BaseComponent from "../../../redare/components/BaseComponent";
import DataSelect from "./DataSelect";
import {UserOutlined} from "@ant-design/icons";
import Member from "../permission/Member";

import DDGatewayPresenter from "../../.gen/presenter/DDGatewayPresenter";
import UserPresenter from "../../../.gen/presenter/UserPresenter";
import {ifTrue} from "../../../redare/utils/Utils";

export default class UserSelect extends BaseComponent {

    static defaultProps = {
        mode: 'multiple', //是否单选,默认多选
        autoRequestData: true, // 是否默认请求数据源
        popupcontainer: undefined, // 挂载滚动节点
        istoloading: false, // 是否显示转换等待
        sysuser: false, // 是否默认将钉钉用户转成系统
        selectValue: []
    };


    // 转换默认提示语句
    defaultConvertTitle = '正在校验选择的用户是否为系统用户';


    // 人员Map
    userMap = {};
    // 转换后的系统用户数据
    sysUserData = null;
    // 钉钉用户转换系统用户是否处于转换中
    dingUserToSysUserIng = undefined;
    // interval调用数据
    intervalGetData = null;
    // 外部赋值时，暂存的临时数据
    _setDataUsers=[];


    constructor(props) {
        super(props);
        this.dd_gatewayPresenter = new DDGatewayPresenter(this);
        this.userPresenter = new UserPresenter(this);

        let selectValue = this.props.selectValue;
        if( ifTrue(selectValue) && selectValue.constructor !== Array ){
            selectValue = [selectValue];
        }

        this.state = {
            selectValue: selectValue,
            spinLoading: false,
            toLoading: false, // 转换等待loading
            convertTitle: this.defaultConvertTitle,
            convertStyle: '', // 转换时样式
            reqError: false, // 转换是否错误
        };
    }

    componentDidMount() {
        this.memberSelect.setSourceLoading();
        if (this.props.autoRequestData) {
            this.loadData();
        }
    }

    componentWillUnmount() {
        if (this.intervalGetData) {
            clearInterval(this.intervalGetData);
        }
    }

    loadData() {
        this.dd_gatewayPresenter.findUsersList({}, {}, (s_r) => {
            if (this.memberSelect) {
                this.setMemberSourceData(s_r.data);
            }
        });
    }

    // 将数据源送外部传递过来
    setMemberSourceData(data) {
        if (data && data.length > 0) {
            // 赋值数据
            let _setDataUsers = this._setDataUsers || [];
            let newUsers = [];
            data.map((item) => {
                this.userMap[item.id] = item;
                _setDataUsers.map((item2)=>{
                    if( ifTrue(item.sysUserId) && item.sysUserId == item2 ){
                        newUsers.push(item.id)
                    }
                });
            });

            // 如果有赋值
            if( this.memberSelect ){
                this.memberSelect.setData(newUsers);
            }

        }
        this.memberSelect.setSourceData(data);
    }


    /**
     * 获取数据
     * @param extFieldArray 需要获取的额外扩展字段一个二维数组，格式为： [ [ 'oldName','newName' ]... ]
     * @returns {Promise<unknown>}
     */
    getData(extFieldArray) {

        let __getData = () => {
            let sysUserData = this.sysUserData || [];
            // 补充额外字段
            if (extFieldArray && extFieldArray.constructor === Array && extFieldArray.length > 0) {
                sysUserData.map((item) => {
                    extFieldArray.map((field) => {
                        item[field[1]] = item[field[0]];
                    });
                });
            }
            return sysUserData;
        }

        return new Promise((resolve, reject) => {
            if (!this.props.sysuser || this.dingUserToSysUserIng === undefined ) {
                resolve(this._getDingUserData());
                return;
            } else {
                // 系统用户处于转换中时，强制打开等待提示语句，并且返回失败回调，
                if (this.dingUserToSysUserIng) {
                    this.setState({toLoading: true, convertStyle: 'form-item-verify-error'});
                    // interval调用数据
                    this.intervalGetData = setInterval(() => {
                        if (!this.dingUserToSysUserIng) {
                            clearInterval(this.intervalGetData);
                            resolve(__getData())
                        }
                    }, 500);
                } else {
                    resolve(__getData())
                }
            }
        });


    }

    getUserData() {
        return this._getDingUserData();
    }

    // 获取钉钉用户数据
    _getDingUserData() {
        let formValues = this.memberSelect.getData();
        if (!formValues) {
            return null;
        }
        let userMap = this.userMap;
        let data = [];
        if (formValues && formValues.constructor !== Array) {
            formValues = [formValues];
        }
        formValues.map((item) => {
            let user = userMap[item];
            let obj = {...user};
            obj['userName'] = obj.name;
            data.push(obj);
        });

        return data;
    }

    // 将钉钉用户转成系统用户
    _dingUserToSysUser() {
        let data = this._getDingUserData();

        if (!data || data.length <= 0) {
            return;
        }
        // 是否显示转换提示
        if (this.props.istoloading) {
            this.setState({toLoading: true});
        }
        // 全局变量处于转换中
        this.dingUserToSysUserIng = true;
        // sate
        this.setState({reqError: false, convertTitle: this.defaultConvertTitle, convertStyle: ''});

        // 开始请求转换服务
        this.userPresenter.dingUserToSysUser(
            {dingUserList: data}, {}, (s_r) => {

                // 将转换后的数据存在全局变量中
                this.sysUserData = s_r.data;
                this.setState({convertTitle: "成功", convertStyle: ''});

                // 延迟0.3秒关闭转换提示
                setTimeout(() => {
                    this.setState({toLoading: false});
                }, 300);
            }, (f_r) => {

                // 转换失败后的处理
                this.setState({
                    reqError: true,
                    toLoading: true,
                    convertTitle: f_r.msg,
                    convertStyle: 'form-item-verify-error'
                });
            }
        );
    }

    closeLoadingIndicator() {
        this.dingUserToSysUserIng = false;
    }

    // 失去焦点时
    __onBlur() {
        // 如果需要返回系统用户才进行转化
        if (this.props.sysuser) {
            this._dingUserToSysUser();
        }
        // 此方法只是为了触此组件被 Form.Item 包裹时的验证
        if( this.props.onChange ){
            this.props.onChange({});
        }
    }

    a(){
        if( this.props.onChange ){
            this.props.onChange();
        }
    }

    /**
     * 获取数据属性的数组
     * @param jointKeysArray ['id','name']
     * @returns {{}|null} 列： {idArray: [1,2,3], nameArray: ['张三', '李四', '王五']}
     */
    getDataByAttr(jointKeysArray = []) {

        return new Promise((resolve, reject) => {
            this.getData().then((userArray) => {

                if (!userArray || userArray.constructor !== Array || userArray.length <= 0) {
                    resolve(null);
                    console.error("数据为null")
                    return;
                }

                let result = {};
                userArray.map((user) => {
                    jointKeysArray.map((jointKey) => {
                        let array = result[jointKey + "Array"] || [];

                        // 如果使用转换，获取 userId 就是获取 sysUserId
                        if( ifTrue(user['sysUserId']) && jointKey === 'userId' && this.props.sysuser ){
                            array.push(user['sysUserId']);
                        }else {
                            array.push(user[jointKey]);
                        }
                        result[jointKey + "Array"] = array;
                    })
                });

                resolve(result);

            });
        });

    }


    // 人员回滚函数
    memberCallBack(formItemKey, selectedMember) {
        let ids = [];
        selectedMember.map((item) => {
            ids.push(item["visitorDataId"]);
        });
        let obj = {};
        obj[formItemKey] = ids;
        this.memberSelect.setData(ids);
        this.memberSelect.focus();
    }

    openSelectMemberByInput(member) {
        let selectData = this.memberSelect.getData() || [];
        if (selectData && selectData.constructor !== Array) {
            selectData = [selectData];
        }
        let formValues = [...selectData] || [];
        let userMap = this.userMap;
        let data = [];
        formValues.map((item) => {
            data.push(userMap[item]);
        });
        member.openWindow(data);
    }

    // 赋值
    setData(users) {

        this._setDataUsers = null;

        if (!users){
            return;
        }
        if( users.toString().indexOf(",") > 0  ){
            users = users.split(",");
        }else if (users.constructor !== Array) {
            users = [users];
        }

        // 存起来将在请求服务器数据后处理
        this._setDataUsers = users;
    }

    render() {
        let mode = this.props.mode;
        return (
            <div className={'select-user ' + this.state.convertStyle}>
                <div className={'input-border'}>
                    <DataSelect
                        ref={(the) => {
                            this.memberSelect = the;
                            if (the) {
                                the.popoverContentFn = (item) => userSelectPopoverContent(item);
                            }
                        }}
                        value={this.state.selectValue}
                        placeholder="请输入"
                        matchkey={"id"}
                        matchname={"name"}
                        mode={mode}
                        tokenSeparators={[',']}
                        bordered={false}
                        showArrow={false}
                        popupcontainer={this.props.popupcontainer}
                        onBlur={() => {
                            this.__onBlur()
                        }}
                    />
                    <UserOutlined onClick={() => {
                        this.openSelectMemberByInput(this.member_operator)
                    }}/>
                    <Member
                        ref={o => this.member_operator = o}
                        callback={(data) => this.memberCallBack('memberValues', data)}
                    />
                </div>
                {/* 加载和错误提示*/}
                <div className={'msg'} style={{marginTop: '2px'}} hidden={!this.state.toLoading}>
                    {
                        !this.state.reqError && <Spin className={'margin-top0'} size="small"/>
                    }
                    <span className={this.state.convertStyle}
                          style={{marginLeft: '10px'}}>{this.state.convertTitle}</span>
                </div>
            </div>
        )
    }

}


// 人员提示内容
let userSelectPopoverContent = function (item) {
    let avatarNode = '';
    let deptNames = item.departmentNames;
    if (item.avatar) {
        avatarNode = <Avatar className={'user-img'} size="large" src={item.avatar}/>;
    } else {
        avatarNode =
            <Avatar className={'user-img'} size="large">
                <UserOutlined style={{fontSize: '22px'}}/>
            </Avatar>;
    }
    if (deptNames) {
        deptNames = deptNames.substring(1, deptNames.length - 1);
    }

    return (
        <div>
            <div style={{marginBottom: '10px'}}>{avatarNode}</div>
            <div>部门：{deptNames}</div>
        </div>
    )
}

export let userSelectPopoverContentNode = userSelectPopoverContent;